package api.connection;

import api.Configuration;
import com.google.gson.Gson;
import com.mongodb.CommandResult;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

public class ConnectionMongo implements DBConnection<MongoClient> {
    private Configuration config;

    public ConnectionMongo(Configuration config) {
        this.config = config;
    }

    public MongoClient makeConnection() {
        MongoClient mongoClient = null;

        try {

            // To connect to mongodb server
            MongoCredential credential = MongoCredential.createCredential(
                    config.getDb_username(),config.getBenchmark(), config.getDb_password().toCharArray());

//            mongoClient = new MongoClient(
//                    new ServerAddress("10.131.141.112",27017), Arrays.asList(credential));
            /*mongoClient = new MongoClient("localhost", 27017);*/
            mongoClient = new MongoClient(config.getDb_connection());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return mongoClient;
    }


    public static void main(String[] args){
        Configuration configTest = new Configuration();
        configTest.setDb_username("root");
        configTest.setDb_password("123456");
        configTest.setBenchmark("tpchdata");
        DBConnection DBconnect = new ConnectionMongo(configTest);

        MongoClient mongoClient = (MongoClient) DBconnect.makeConnection();
    }

    private static class TestMongoConnection {
        public static void main(String[] args) {
            InputStream configStream = ConnectionMongo.class.getClassLoader().getResourceAsStream("config.json");
            Configuration config = new Gson().fromJson(new InputStreamReader(configStream), Configuration.class);
            ConnectionMongo connectionMongo = new ConnectionMongo(config);
            MongoClient mongoClient = connectionMongo.makeConnection();
            CommandResult status = mongoClient.getDB("tpch").getStats();

            System.out.println("ok");
        }
    }
}
